﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using Facebook;
using System.Windows.Controls.Primitives;
using ThuPhap.Controls;
using System.Windows.Threading;
using ThuPhap.Class;

namespace ThuPhap.Facebook
{
    public partial class SharePage : PhoneApplicationPage
    {
        public string Token { get; set; }
        public string Filename { get; set; }
        public bool IsLoaded { get; set; }
        private BitmapImage bm;
        public delegate void TokenExpired();
        public static event TokenExpired TokenExpiredEvent;
        public SharePage()
        {
            InitializeComponent();
            
            this.IsLoaded = false;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string accessToken, filename,type,id;
            if (NavigationContext.QueryString.TryGetValue("token", out accessToken) && NavigationContext.QueryString.TryGetValue("type", out type) && NavigationContext.QueryString.TryGetValue("filename", out filename) && NavigationContext.QueryString.TryGetValue("id", out id))
            {
                this.Token = accessToken;
                this.Filename = filename;
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(filename, FileMode.Open, FileAccess.Read))
                    {
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.SetSource(fileStream);
                        bm = bitmap;
                        //wb.SetSource(fileStream);
                        DataContext = bitmap;
                        fileStream.Close();
                    }
                }
                
                if ((!IsLoaded) && type == "login")
                {
                    NavigationService.RemoveBackEntry();
                    IsLoaded = true;
                }
            }
        }

        private void CaptionTextbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            
        }

        private void CaptionTextbox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (CaptionTextbox.Text == "add a caption")
            {
                CaptionTextbox.Text = "";
                //CaptionTextbox.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        private void CaptionTextbox_KeyUp(object sender, KeyEventArgs e)
        {
            if (CaptionTextbox.Text == "")
            {
                //CaptionTextbox.Text = "add a caption";
                //CaptionTextbox.Foreground = new SolidColorBrush(Colors.Gray);
            }
            else
            {
                CaptionTextbox.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        private void CaptionTextbox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (CaptionTextbox.Text == "")
            {
                CaptionTextbox.Text = "add a caption";
                CaptionTextbox.Foreground = new SolidColorBrush(Colors.Gray);
            }
        }

        DispatcherTimer timer = new DispatcherTimer();
        Popup popup;
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            popup = new Popup() { Child = new LoadingControl("Uploading ..."), IsOpen = true };
            timer.Interval = TimeSpan.FromSeconds(1.5);
            

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.sharePhoto(this.Filename, this.Token);
            });
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            popup.IsOpen = false;
            NavigationService.GoBack();
            timer.Stop();

        }

        private void sharePhoto(string FileName, string AccessToken)
        {
            var fb = new FacebookClient(AccessToken);
            fb.PostCompleted += (o, args) =>
            {
                if (args.Error != null)
                {
                    if (args.Error.Message.StartsWith("(OAuthException - #190)"))
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            // Error 190 means that the token has expired. You need to ask the user to get the token again before continuing. Handle this error gracefully here.
                            MessageBox.Show("Token has expired.\nYou need to login to facebook again!", "Notice", MessageBoxButton.OK);
                            SerializeHelper.DeleteToken();
                            if (TokenExpiredEvent != null)
                            {
                                TokenExpiredEvent();
                            }
                        });
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(args.Error.Message, "Error", MessageBoxButton.OK);
                        });
                    }
                    return;
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Upload successfully","Notice",MessageBoxButton.OK);
                    }
                );
                }
            };

            var file = new FacebookMediaObject()
            {
                FileName = FileName,
                ContentType = "image/jpg",
            };

            using (MemoryStream ms = new MemoryStream())
            {
                WriteableBitmap btmMap = new WriteableBitmap(bm);

                // write an image into the stream
                Extensions.SaveJpeg(btmMap, ms,
                    bm.PixelWidth, bm.PixelHeight, 0, 100);

                var data =  ms.ToArray();
                file.SetValue(data);
            }

            var parameters = new Dictionary<string, object>();
            string caption = this.CaptionTextbox.Text == "add a caption" ? "" : this.CaptionTextbox.Text;
            string ad = "\n\n***Image is uploaded from Vietnamese Calligraphy Application http://www.windowsphone.com/s?appid=52e63152-faba-44b4-a30a-1486b8300e89***";
            parameters["message"] = caption + ad;
            parameters["file"] = file;

            fb.PostAsync("me/photos", parameters);
        }
    }
}